package com.scnlf.scnlf.portal.core.common.utils;

import java.util.Optional;
import org.springframework.expression.EvaluationContext;
import org.springframework.expression.Expression;
import org.springframework.expression.ExpressionParser;
import org.springframework.expression.spel.standard.SpelExpressionParser;
import org.springframework.expression.spel.support.StandardEvaluationContext;

public class SpelExpressionUtils {

    public static String getStringValue(Object object, String expressionStr){
        ExpressionParser parser = new SpelExpressionParser();
        Expression expression = parser.parseExpression(expressionStr);
        EvaluationContext context = new StandardEvaluationContext();
        context.setVariable("context", object);
        return Optional.ofNullable(expression.getValue(context)).map(obj -> obj.toString()).orElse(null);
    }

}
